package cn.edu.sctu.sctu_lysd.view.act;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.utils.Log;

import java.io.FileNotFoundException;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.JsonBaseListBean;
import cn.edu.sctu.sctu_lysd.bean.ParcelData;
import cn.edu.sctu.sctu_lysd.cofig.CacheKeyConfig;
import cn.edu.sctu.sctu_lysd.databinding.ActivityQrCodeBinding;
import cn.edu.sctu.sctu_lysd.net.NetService;
import cn.edu.sctu.sctu_lysd.net.RetrofitHelper;
import cn.edu.sctu.sctu_lysd.utils.CompressImgUtil;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.ProgressUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wangfuxin on 2017-04-21.
 */

public class QRCodeAct extends BaseActivity {

    public static final String INTENT_PARCEL_ID = "intent_parcel_id";
    private String QRCodeStr;
    private long parcelId;
    private ActivityQrCodeBinding mBinding;

    private Bitmap mBitmap = null;

    private Handler handler;

    private ProgressUtil progressUtil;

    private ProgressDialog progressDialog;

    private int SUCCESS_MESSAGE = 11;
    private int Failed_MESSAGE = 11;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_qr_code;
    }

    @Override
    protected void initAfter(Object bind) {

        mBinding = (ActivityQrCodeBinding) bind;

        progressUtil = ProgressUtil.getInstance(this);

        getIntentData();

        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == SUCCESS_MESSAGE) {

                    progressUtil.dismiss(progressDialog);

                    Toast.makeText(QRCodeAct.this,"图片成功保存至" + CacheKeyConfig.SAVE_FILE_HOME,Toast.LENGTH_LONG).show();

                    ProgressUtil.showAlertDialog("保存成功", "点击确定查看我的包裹", QRCodeAct.this, new ProgressUtil.AlertDialogCallBack() {
                        @Override
                        public void submit() {
                            JumpUtils.jumpActivity(QRCodeAct.this,MyOrdersActivity.class);
                            finish();
                        }

                        @Override
                        public void cancel() {

                            JumpUtils.jumpActivity(QRCodeAct.this,IndexActivity.class);
                            finish();

                        }
                    });

                    return;

                }

                if (msg.what == Failed_MESSAGE) {

                    progressUtil.dismiss(progressDialog);

                    Toast.makeText(QRCodeAct.this,"保存失败，请重试或请检查权限",Toast.LENGTH_LONG).show();

                }

            }
        };


    }


    private void getIntentData() {

        parcelId = getIntent().getExtras().getLong(INTENT_PARCEL_ID);

        QRCodeStr = RetrofitHelper.BASE_URL + NetService.ROOT_URL + "/parcels/" + parcelId + "/qrcode";

        getParcel(parcelId);
    }

    private void createQRCodeImg(String QRCodeStr) {
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(QRCodeStr, BarcodeFormat.QR_CODE, 800, 800);
            // 使用 ZXing Android Embedded 要写的代码
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = barcodeEncoder.createBitmap(result);
            mBitmap = bitmap;

        } catch (Exception iae) {

        }

    }


    public void saveImageToGallery(final Context context, final String fileName, final Bitmap bitmap) {

        new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                // 首先保存图片
                CompressImgUtil.getInstance().saveFIle(CacheKeyConfig.SAVE_FILE_HOME, fileName, bitmap);

                // 其次把文件插入到系统图库

                    MediaStore.Images.Media.insertImage(context.getContentResolver(),
                            CacheKeyConfig.SAVE_FILE_HOME, fileName, null);

                    // 最后通知图库更新
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.parse("file://" + CacheKeyConfig.SAVE_FILE_HOME + "/" + fileName)));

                    handler.sendEmptyMessage(SUCCESS_MESSAGE);

                } catch (java.io.IOException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(Failed_MESSAGE);
                }

            }
        }.start();

    }


    private void getParcel(long parcelId) {

        RetrofitHelper helper = RetrofitHelper.getInstance();

        NetService service = (NetService) helper.getService(NetService.class);

        service.getOneParcel(parcelId).enqueue(new Callback<JsonBaseListBean<ParcelData>>() {
            @Override
            public void onResponse(Call<JsonBaseListBean<ParcelData>> call, final Response<JsonBaseListBean<ParcelData>> response) {
                if (response.code() == 200 && response.body().getMeta().getCode() == 200) {

                    //创建二维码
                    createQRCodeImg(QRCodeStr);
                    mBinding.qrCodeImg.setImageBitmap(mBitmap);

                    mBinding.qrCodeSaveImg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, false, "loding");

                            if (mBitmap != null) {
                                saveImageToGallery(QRCodeAct.this,
                                        response.body().getData().get(0).getName() + ".jpeg",
                                        mBitmap);
                            }

                        }
                    });

                    mBinding.qrCodeShareImg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mBitmap != null) {
                                new ShareAction(QRCodeAct.this)
                                        .withText(response.body().getData().get(0).getName())
                                        .withMedia(new UMImage(QRCodeAct.this,mBitmap))
                                        .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)
                                        .setCallback(umShareListener)
                                        .open();
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<JsonBaseListBean<ParcelData>> call, Throwable t) {

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            ProgressUtil.showAlertDialog("分享成功", "点击确定查看我的包裹", QRCodeAct.this, new ProgressUtil.AlertDialogCallBack() {
                @Override
                public void submit() {
                    JumpUtils.jumpActivity(QRCodeAct.this,MyOrdersActivity.class);
                    finish();
                }

                @Override
                public void cancel() {

                    JumpUtils.jumpActivity(QRCodeAct.this,IndexActivity.class);
                    finish();

                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(QRCodeAct.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

        }
    };

}
